package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.entity.User;
import com.example.service.IUserService;
import com.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Author: lfanh
 * Date: 2022/11/6 0:07
 */
@RestController
@RequestMapping(value = "user",produces = "application/json;charset=utf-8")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @PostMapping("login")
    public R<User> login(HttpServletRequest request, @RequestBody User user){

        //1、将页面提交的密码进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据提交的登录名查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getCode,user.getCode());
        User user1 = iUserService.getOne(queryWrapper);

        //3、未查询出该用户则返回登录失败
        if(user1 == null){
            return R.error("登录失败！");
        }
        //4、校验密码，不一致则返回登录失败
        if(! user1.getPassword().equals(password)){
            return R.error("登录失败！");
        }
        //5、验证账号状态是否异常
        if(user1.getStatus() != 1){
            return R.error("你已被封号！");
        }

        //6、登录成功，将账号id存入Session并返回登录成功
        request.getSession().setAttribute("user",user1.getId());
        return R.success(user1);
    }


    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){

        //清理当前Session中保存的管理员id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");

    }

    @GetMapping
    public List<User> getAll(){
        return iUserService.list();
    }

    @PostMapping
    public Boolean save(@RequestBody User user){
        return iUserService.save(user);
    }

    @GetMapping("{id}")
    public User getById(@PathVariable Integer id){
        return iUserService.getById(id);
    }

    @PutMapping
    public Boolean update(@RequestBody User user){
        return iUserService.updateById(user);
    }

    @DeleteMapping("{id}")
    public Boolean delete(@PathVariable Integer id){
        return iUserService.removeById(id);
    }

    @GetMapping("{currentPage}/{pageSize}")
    public IPage<User> getPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize){
        return iUserService.getPage(currentPage,pageSize);
    }
}
